import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Location } from '@angular/common';

import 'rxjs/add/operator/switchMap';

import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component({
    selector: 'hero-detail',
    templateUrl: './hero-detail.component.html',
    styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
    hero: Hero;
    constructor(private heroService: HeroService, private router: ActivatedRoute, private location: Location) { }
    ngOnInit(): void {
        // 加号是将字符串转换为数字
        this.router.paramMap
        .switchMap((param: ParamMap) => this.heroService.getHero(+param.get('id')))
        .subscribe(hero => this.hero = hero);
    }
    goBack(): void {
        this.location.back();
    }

    save(): void {
        this.heroService.update(this.hero).then(() => this.goBack());
    }
}

